package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.Page;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

//检查套餐 Controller
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    private SetmealService setmealService;

    //查询(回显)所有检查组
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    @RequestMapping("/findAll")
    public Result findAll(){

        try {
//            查询成功
            List<CheckGroup> checkGroupList = setmealService.findAll();
            return new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS,checkGroupList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_CHECKGROUP_FAIL);
        }

    }

    //套餐图片上传
    @RequestMapping("/upload")
    @PreAuthorize("hasAuthority('SETMEAL_ADD')")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) throws InterruptedException {

        //Thread.currentThread().sleep(2000);
        try {
            String OriginalFilename = imgFile.getOriginalFilename();//获取图片的完整Name;
            int index = OriginalFilename.lastIndexOf(".");  //获取名字中最后一个" ."的索引
            String substring = OriginalFilename.substring(index); //截取从该索引开始到尾部的字符串  如:  .jsp
            String string = UUID.randomUUID().toString();  //通过UUID 获取一个字符串 给图片命名(以妨重名 所以推荐使用UUID生成)
            String fileName = string + substring;  //与上面截取下来的图片格式进行拼接,造出一个完整的名称

            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);  // 使用七牛云工具类,将该图片传到七牛云云端

            //将上传的图片名字添加到redis缓存数据库
            JedisPool jedisPool = new JedisPool();
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);

            return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,fileName);  //图片上传成功

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);  //图片上传失败
        }

    }

    //添加套餐
    @RequestMapping("/add")
    @PreAuthorize("hasAuthority('SETMEAL_ADD')")
    public Result add(@RequestBody Setmeal setmeal , Integer [] checkgroupIds ){
        try {

                    //延时语句
            //Thread.currentThread().sleep(5000);//毫秒
            setmealService.add(setmeal,checkgroupIds);

//            将上传到云端以及添加到数据库的图片名字添加到redis数据库
            if(setmeal.getImg()!=null) {
                JedisPool jedisPool = new JedisPool();
                jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
            }

            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }


    }
    //分页查询所有套餐
    @RequestMapping("/query")
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    public Result query(@RequestBody QueryPageBean queryPageBean){
        try {
            Integer currentPage = queryPageBean.getCurrentPage();//当前页数
            Integer pageSize = queryPageBean.getPageSize();//每页显示的条数
            String queryString = queryPageBean.getQueryString();//查询条件
           // System.out.println(queryString);
            PageResult _querySetmealAll = setmealService.query(currentPage, pageSize, queryString);
            Long total = _querySetmealAll.getTotal(); //总记录数
            int _currentPage =(int) Math.ceil((total*1.0) / (pageSize*1.0));//总页数
//            System.out.println("总记录数"+total);
//            System.out.println("数据库查出真实的总页数"+_currentPage);
//            System.out.println("要查的当前页数"+currentPage);
            /*
            * _currentPage  当前数据库查出的真实的总页数
            * currentPage   前端传过来的要查的当前页码
            * 如果要查的当前页码大于真实的总页数,那么就需要把当前页码的值赋值给总页数进行重新查询并返回
            * */
            if(currentPage>_currentPage){
                PageResult querySetmealAll = setmealService.query(_currentPage, pageSize, queryString);
                return new Result(true,MessageConstant.QUERY_SETMEALLIST_SUCCESS,querySetmealAll);
            }
            return new Result(true,MessageConstant.QUERY_SETMEALLIST_SUCCESS,_querySetmealAll);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_SETMEALLIST_FAIL);
        }
    }


    //编辑套餐 (回显套餐普通数据)
    @RequestMapping("/queryById")
    //权限控制
    public Result queryById(Integer id){
        try {
            Setmeal setmeal = setmealService.queryById(id);
            return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

    //编辑套餐(回显该套餐拥有那些检查组)
    @RequestMapping("/checkgroupIds")
    public Result checkgroupIds(Integer id){
        try {
            List<Integer> checkgroupIds = setmealService.checkgroupIds(id);
            return new Result(true,MessageConstant.QUERY_CHECKGROUP_SUCCESS,checkgroupIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_CHECKGROUP_FAIL);
        }

    }


    //编辑套餐
    @RequestMapping("/update")
    @PreAuthorize("hasAuthority('SETMEAL_EDIT')")
    public Result Update(Integer [] checkgroupIds,@RequestBody Setmeal setmeal){
        try {
            //System.out.println(Arrays.toString(checkgroupIds));
            //System.out.println(setmeal);
            setmealService.Update(checkgroupIds,setmeal);
            return new Result(true,MessageConstant.EDIT_SETMEAL_SUCCESS);
        } catch (Exception e) {
            return new Result(false,MessageConstant.EDIT_SETMEAL_FAIL);
        }

    }

    //清除预约人数,删除套餐(根据ID)
    @RequestMapping("/DeleteById")
    @PreAuthorize("hasAuthority('SETMEAL_DELETE')")
    public Result DeleteById(Integer id){
        try {
            setmealService.DeleteById(id);
            return new Result(true,MessageConstant.DELETE_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_SETMEAL_FAIL);
        }
    }

    //查询该套餐是否有人预约
    @RequestMapping("QueryOrderNumber")
    public Result QueryOrderNumber(Integer id){
        try {
            Integer OrderNumber = setmealService.QueryOrderNumber(id);
            System.out.println("套餐ID"+id);
            System.out.println("套餐预约人数"+OrderNumber);
            return new Result(true,MessageConstant.DELETE_SETMEAL_SUCCESS,OrderNumber);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_SETMEAL_FAIL);
        }
    }

    //删除套餐,并发送预约失效通知短信
    @RequestMapping("/DeleteByIdNote")
    public Result DeleteByIdNote(Integer id){
        try {
            setmealService.DeleteByIdNote(id);
            return new Result(true,MessageConstant.DELETE_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.DELETE_SETMEAL_FAIL);

        }
    }


}
